<?php
declare(strict_types=1);

namespace Dreamcat\ApolloPhp\Impl\Saver;

use Dreamcat\ApolloPhp\ConfigSaverInterface;
use Dreamcat\ApolloPhp\Popo\ConfigResult;

/**
 * 考虑swoole修改配置后需要发送信号重启
 * @author vijay
 */
class SwooleSaver implements ConfigSaverInterface
{
    /** @var ConfigSaverInterface 基准保存器 */
    private $baseSaver;
    /** @var string pid文件 */
    private $pidFile;
    /** @var int 要发送的信号 */
    private $sign;

    /**
     * SwooleSaver constructor.
     * @param ConfigSaverInterface $baseSaver
     * @param string $pidFile
     * @param int $sign
     */
    public function __construct(ConfigSaverInterface $baseSaver, string $pidFile, int $sign = SIGUSR1)
    {
        $this->baseSaver = $baseSaver;
        $this->pidFile = $pidFile;
        $this->sign = $sign;
    }

    /**
     * @inheritDoc
     */
    public function saveConfig(ConfigResult $configResult): bool
    {
        return $this->baseSaver->saveConfig($configResult);
    }

    /**
     * @inheritDoc
     */
    public function onSaveAll(): void
    {
        $this->baseSaver->onSaveAll();
        if (is_file($this->pidFile) && is_readable($this->pidFile)) {
            posix_kill(intval(file_get_contents($this->pidFile)), $this->sign);
        }
    }
}

# end of file
